import mqtt from "mqtt";
const options = {
  protocol: "ws", //使用WebSocket Secure (wss) 连接，或 'ws' 如果不使用SSL
  hostname: "115.159.50.118", // MQTT Broker的URL
  port: "15675", // MQTT Broker的端口
  path: "/ws", // 通常WebSocket连接路径
  clientId: "myclientid_" + parseInt(Math.random() * 100, 10), // 客户端ID
  username: "guest", // 用户名
  password: "guest", // 密码
};
const client = mqtt.connect(options);
client.on("connect", () => {
  console.log("连接成功");
});
client.on("error", (error) => {
  console.log("连接失败", error);
  client.end();
});
client.on("reconnect", () => {
  console.log("正在重连");
});
client.on("message", (topic, message) => {
  console.log(`Received message from ${topic}: ${message.toString()}`);
});

const mqttService = {
  subscribe: (topic) => {
    client.subscribe(topic, (err) => {
      if (!err) {
        console.log(`Subscribed to ${topic}`);
      } else {
        console.error(`Subscription error: ${err}`);
      }
    });
  },
  onMessage: (callback) => {
    client.on("message", callback);
  },
};

export default mqttService;
